#include "CServer.h"
#include <iostream>
#include "HttpConnection.h"
#include "AsioIOServicePool.h"

CServer::CServer(net::io_context& io_context,unsigned short port)
:acceptor_(io_context,tcp::endpoint(tcp::v4(),port))
{

}

void CServer::Start()
{
    auto self(shared_from_this());
    //获取io_context
    auto& io_context = AsioIOServicePool::GetInstance()->GetIOService();
    std::shared_ptr<HttpConnection> conn = std::make_shared<HttpConnection>(io_context);

    acceptor_.async_accept(conn->GetSocket(),[self,conn](const boost::system::error_code& ec){
        try
        {
            if(ec)
            {
                self->Start();
                std::cerr<<"accept error:"<<ec.message()<<std::endl;
                return;
            }

            conn->Start();
            self->Start();
        }
        catch(const std::exception& e)
        {
            std::cerr << "accept error:" << e.what() << '\n';
            self->Start();
        }

        
    });
}